#include "music_player.h"
#include "ui_music_player.h"

#include <QAudioOutput>
#include <QFileDialog>
#include <QJsonDocument>
#include <QMessageBox>
#include <QRandomGenerator>


music_player::music_player(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::music_player)
{
    ui->setupUi(this);

    //唱片图片
    QPixmap pixmap;
    pixmap.load(":/img/deiSaHaO5F.png");
    // pixmap.scaled(50, 50);
    ui->label_png->setPixmap(pixmap);


    QFile file("./music_list");
    if (file.open(QIODevice::ReadOnly)) {
        QTextStream in(&file);
        QString str = in.readAll();
        file.close();
        QStringList list = str.split("\n");
        for(int i=0;i<list.size()-1;i+=2){
            ui->music_list->addItem(list[i]);
            play_list.push_back(list[i+1]);
        }
    }else{
        qDebug() << "打开文件失败" << file.errorString();
    }
    this->http = new QNetworkAccessManager(this);
    this->player = new QMediaPlayer;
    audioOutput = new QAudioOutput;
    player->setAudioOutput(audioOutput);
    connect(player, SIGNAL(positionChanged(qint64)), this, SLOT(positionChanged(qint64)));

    audioOutput->setVolume(0.5);
    ui->music_volum->setValue(50);

    //修改音量
    connect(ui->music_volum,&QSlider::valueChanged,this,[=](){
        audioOutput->setVolume(ui->music_volum->value()/100.0);
    });

    //搜索按钮
    connect(ui->btn_search,&QPushButton::clicked,this,&music_player::send_request);
    connect(this->http,&QNetworkAccessManager::finished,this,&music_player::handle_request);

    //双击歌曲播放
    connect(ui->music_list,&QListWidget::doubleClicked,this,[=](){
        ui->btn_play->setText("暂停");
        this->current_music = ui->music_list->currentRow();
        player->setSource(QUrl(this->play_list[current_music]));
        player->play();
    });
    //播放状态改变：
    connect(this->player,&QMediaPlayer::mediaStatusChanged,this,&music_player::onStateChanged);

    //删除列表中的歌曲
    connect(ui->btn_delete,&QPushButton::clicked,this,[=](){
        int index = ui->music_list->currentRow();
        ui->music_list->takeItem(index);
        this->play_list.remove(index);
        if(play_list.size() == 0)
            current_music = 0;
        else
            this->current_music%=this->play_list.size();
    });

    //点击下一首按钮
    connect(ui->btn_next,&QPushButton::clicked,this,[=](){
        if(play_list.empty())
            return;
        switch(ui->play_model->currentIndex()){
            case 0:
                current_music++;
                current_music%=play_list.size();
                break;
            case 1:
                if(current_music < play_list.size()-1)
                    ++current_music;
                break;
            case 3:
                current_music = QRandomGenerator::global()->bounded(0, play_list.size());
                break;
            default:
                break;
        };
        ui->music_list->setCurrentRow(current_music);
        player->setSource(QUrl(this->play_list[current_music]));
        player->play();
    });

    //点击上一首按钮：
    connect(ui->btn_pre,&QPushButton::clicked,this,[=](){
        if(play_list.empty())
            return;
        switch(ui->play_model->currentIndex()){
        case 0:
            current_music += play_list.size() - 1;
            current_music%=play_list.size();
            break;
        case 1:
            if(current_music>0)
                --current_music;
            break;
        case 3:
            current_music = QRandomGenerator::global()->bounded(0, play_list.size());
            break;
        default:
            break;
        };
        ui->music_list->setCurrentRow(current_music);
        player->setSource(QUrl(this->play_list[current_music]));
        player->play();
    });

    //点击 播放/暂停 按钮
    connect(ui->btn_play,&QPushButton::clicked,this,[=](){
        if(ui->btn_play->text() == "播放"){
            ui->btn_play->setText("暂停");
            this->player->play();
        }else if(ui->btn_play->text() == "暂停"){
            ui->btn_play->setText("播放");
            this->player->pause();
        }
    });

    //播放进度绑定：
    connect(player,&QMediaPlayer::positionChanged,this,[=](qint64 position){

        if (player->duration() > 0 && !ui->scheduleSlider->isSliderDown()) {
            // 计算当前播放进度，并设置给QSlider
            int value = static_cast<int>(position * 100 / player->duration());
            int minue_time=0,second_time=0;
            minue_time = position/1000/60,second_time = (position/1000)%60;
            ui->label_now_time->setText(QString::number(minue_time)+" : "+QString::number(second_time));
            minue_time = player->duration()/1000/60,second_time = (player->duration()/1000)%60;
            ui->label_sum_time->setText(QString::number(minue_time)+" : "+QString::number(second_time));

            ui->scheduleSlider->setValue(value);
        }
    });
    connect(ui->scheduleSlider,&QSlider::sliderMoved,this,[=](int value){
        qint64 position = value * player->duration() / 100;
        player->setPosition(position);
    });

    //添加本地音乐
    connect(ui->btn_add,&QPushButton::clicked,this,[=](){
        QStringList data = QFileDialog::getOpenFileNames(
            this,
            "添加音乐","E:\\woke\\QT_Pro\\2311\\Day9\\media","*.mp3 *.wav");

        //将音乐添加到音乐播放链表，同时同步到 ui 显示链表
        for(int i = 0;i < data.size();i++)
        {
            this->play_list.push_back(QUrl::fromLocalFile(data[i]));
            //将名字同步到 ui 显示界面
            QFileInfo info(data[i]);//获取文件名字  -> 文件名就是音乐名
            ui->music_list->addItem(info.fileName());
        }
    });
}

//点击搜索按钮
void music_player::send_request(){
    for(int i=1;i<=3;++i){
        QString url = "https://api.yaohud.cn/api/music/qq?key=kfvPymy4ZSQF9KP152W&msg=" + ui->line_search->text()
                      + "&n=" + QString::number(i)+ "&size=mp3";
        this->http->get(QNetworkRequest(QUrl(url)));
    }

}

//接收到网络数据
void music_player::handle_request(QNetworkReply *reply){
    //先看状态码
    int statu = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if(statu != 200)
    {
        QMessageBox::critical(this,"网络错误","找不到信息");
        return;
    }

    QByteArray data = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);

    if(doc.isObject())
    {
        QJsonObject music_data = doc.object()["data"].toObject();
        ui->music_list->addItem(music_data["name"].toString()+" "+music_data["songname"].toString());
        this->play_list.push_back(QUrl(music_data["musicurl"].toString()));
        QString lrc_url = music_data["lrc"].toString();

    }
}

//播放状态改变：
void music_player::onStateChanged(QMediaPlayer::MediaStatus state)
{
    qDebug() << state;
    //歌曲播放完
    if (state == QMediaPlayer::EndOfMedia)
    {
        emit ui->btn_next->clicked();
    }
}


music_player::~music_player()
{
    QFile file("./music_list");
    if (file.open(QIODevice::WriteOnly)) {
        QTextStream out(&file);
        for(int i=0;i<play_list.size();++i){
            out << ui->music_list->item(i)->text() << "\n";
            out << play_list[i].toString() << "\n";
        }
        file.close();
    }else{
        qDebug() << "打开文件失败" << file.errorString();
    }
    delete ui;
    delete http;
    delete player;
    delete audioOutput;
}
